package com.feeyo.groundservice.vehiclemonitorserver;

import com.feeyo.groundservice.base.rdb.PostgresDb;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by fooevr on 2016/12/28.
 */
public class Department extends AbstractVerticle {
	
	Logger logger = LoggerFactory.getLogger(Department.class);
    public static Map<String, DepartmentObject> departments = new HashMap();

    @Override
    public void start(Future<Void> startFuture) throws Exception {
    	try{
        PostgresDb.postgreSQLClient.getConnection(conn->{
            if(conn.failed()){
                System.out.println(conn.cause());
                return;
            }
            if(conn.succeeded()){
	            conn.result().query("select id, name, parentid, code from common.department where not _deleted", r->{
	                conn.result().close();
	                if(r.failed()){
	                    System.out.println(r.cause());
	                    return;
	                }
	                departments.clear();
	                for(int i = 0; i < r.result().getNumRows(); i++){
	                    JsonObject row = r.result().getRows().get(i);
	                    DepartmentObject dep = new DepartmentObject();
	                    dep.id = row.getString("id");
	                    dep.name = row.getString("name");
	                    dep.parentId = row.getString("parentid");
	                    dep.code = row.getString("code");
	                    departments.put(dep.id, dep);
	                }
	                logger.info("load department " + departments.size());
	                startFuture.complete();
	            });
            }
        });
    	}catch (Exception e){
    		e.printStackTrace();
    	}
    }
    public class DepartmentObject{
        public String name;
        public String id;
        public String parentId;
        public String code;
    }
}
